package leetcode_day._2022._202208._1120;

/**
 * 641. 设计循环双端队列
 * 算法：数组
 *
 * @author yzh
 * @version 1.0
 * @date 2022/8/15 21:44
 */
public class _15 {

    class MyCircularDeque {

        int[] nums;
        int he = 0, ta = 0, cnt = 0, k;

        public MyCircularDeque(int _k) {
            k = _k;
            nums = new int[k];
        }

        public boolean insertFront(int value) {
            if (isFull()) return false;
            // 防止负值溢出
            he = (he - 1 + k) % k;
            nums[he] = value;
            ++cnt;
            return true;
        }

        public boolean insertLast(int value) {
            if (isFull()) return false;
            nums[ta] = value;
            ta = (ta + 1) % k;
            ++cnt;
            return true;
        }

        public boolean deleteFront() {
            if (isEmpty()) return false;
            he = (he + 1) % k;
            --cnt;
            return true;
        }

        public boolean deleteLast() {
            if (isEmpty()) return false;
            ta = (ta - 1 + k) % k;
            --cnt;
            return true;
        }

        public int getFront() {
            return isEmpty() ? -1 : nums[he];
        }

        public int getRear() {
            return isEmpty() ? -1 : nums[(ta - 1 + k) % k];
        }

        public boolean isEmpty() {
            return cnt == 0;
        }

        public boolean isFull() {
            return cnt == k;
        }
    }

}
